const WebSocket = require("ws");
// 存储所有的 WebSocket 连接
const connections = new Map();

// 生成唯一的连接 ID
function generateConnectionId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
}

// 封装 WebSocket 处理逻辑的公共函数
function setupWebSocket(server) {
    const wss = new WebSocket.Server({ noServer: true });
    // 处理新的 WebSocket 连接事件
    wss.on("connection", (ws, request) => {
        const url = new URL(request.url, `ws://${request.headers.host}`);
        const userId = url.searchParams.get('userId');
        if (!userId) {
            ws.close(1008, 'Missing userId parameter');
            return;
        }

        const connectionId = generateConnectionId();
        connections.set(userId, ws);

        // 处理接收到的消息
        ws.on("message", async (message) => {
            try {
                const parsedMessage = JSON.parse(message);
                const targetUserId = parsedMessage.targetUserId; // 假设消息中包含目标用户 ID

                if (targetUserId) {
                    const targetClient = connections.get(targetUserId);
                    if (targetClient && targetClient.readyState === WebSocket.OPEN) {
                        await sendAsync(targetClient, `User ${userId} (Connection ${connectionId}) sent: ${parsedMessage.content}`);
                    } else {
                        await sendAsync(ws, `Target user ${targetUserId} is not available or offline.`);
                    }
                } else {
                    await sendAsync(ws, 'Missing targetUserId in the message.');
                }
            } catch (error) {
                console.error('Error parsing message:', error);
                await sendAsync(ws, 'Invalid message format. Please send a valid JSON object with targetUserId and content.');
            }
        });

        // 处理连接关闭事件
        ws.on("close", () => {
            connections.delete(userId);
        });

        // 处理连接错误事件
        ws.on("error", (error) => {
            console.error(`Connection ${connectionId} for user ${userId} error:`, error);
        });
    });

    // 监听服务器的 upgrade 事件，处理 HTTP 到 WebSocket 的升级
    server.on("upgrade", (request, socket, head) => {
        if (request.url.startsWith("/ws")) {
            wss.handleUpgrade(request, socket, head, (ws) => {
                wss.emit("connection", ws, request);
            });
        }
    });

    // 封装 send 方法为异步方法
    function sendAsync(ws, message) {
        return new Promise((resolve, reject) => {
            ws.send(message, (error) => {
                if (error) {
                    console.error('Error sending message:', error);
                    reject(error);
                } else {
                    resolve();
                }
            });
        });
    }

    // 新增广播消息方法
    async function broadcastMessage(message) {
        const sendPromises = [];
        connections.forEach((client) => {
            if (client.readyState === WebSocket.OPEN) {
                sendPromises.push(sendAsync(client, message));
            }
        });
        await Promise.all(sendPromises);
    }

    // 新增向特定用户发送消息的方法
    async function sendMessageToUser(targetUserId, message) {
        const targetClient = connections.get(targetUserId);
        if (targetClient && targetClient.readyState === WebSocket.OPEN) {
            await sendAsync(targetClient, message);
        } else {
        }
    }

    return { wss, broadcastMessage, sendMessageToUser };
}

module.exports = { setupWebSocket };